// 优化版本的数据聚合模块
// 基于小时累计值进行日、最近7天、最近30天的汇总计算

// 常量定义（可配置）
const CONFIG = {
    RETENTION: {
        DAILY_DAYS: 1,      // 保留当天数据
        WEEKLY_DAYS: 7,     // 保留最近7天数据
        MONTHLY_DAYS: 30,   // 保留最近30天数据
        YEARLY_MONTHS: 12   // 保留最近12个月数据
    },
    PRECISION: 2            // 数值精度（小数位数）
};

// 工具函数：格式化数值
function formatNumber(value) {
    return Number(value.toFixed(CONFIG.PRECISION));
}

// 工具函数：生成日期范围
function generateDateRange(startDate, days) {
    const dates = [];
    for (let i = 0; i < days; i++) {
        const date = new Date(startDate);
        date.setDate(date.getDate() - i);
        dates.push(date.toISOString().slice(0, 10));
    }
    return dates;
}

// 工具函数：生成月份范围
function generateMonthRange(startDate, months) {
    const monthKeys = [];
    for (let i = 0; i < months; i++) {
        const date = new Date(startDate);
        date.setMonth(date.getMonth() - i);
        monthKeys.push(date.toISOString().slice(0, 7));
    }
    return monthKeys;
}

// 调试函数
function debugLog(message, data) {
    node.warn(`AGGREGATE DEBUG - ${message}: ${JSON.stringify(data)}`);
}

// 数据聚合核心类
class DataAggregator {
    constructor(hourlyData) {
        this.hourlyData = hourlyData || {};
        this.currentDate = new Date();
        this.currentDay = this.currentDate.toISOString().slice(0, 10);
        this.currentMonth = this.currentDate.toISOString().slice(0, 7);
        this.currentYear = this.currentDate.getFullYear().toString();
    }

    // 从小时数据中聚合指定日期的数据（当天所有小时累计值的汇总）
    aggregateByDate(targetDate) {
        const dayStats = {};
        
        Object.keys(this.hourlyData).forEach(hourKey => {
            if (hourKey.startsWith(targetDate)) {
                const hourData = this.hourlyData[hourKey];
                Object.keys(hourData).forEach(pointId => {
                    if (!dayStats[pointId]) {
                        dayStats[pointId] = 0;
                    }
                    // 累加该测点当天所有小时的sum值
                    dayStats[pointId] = formatNumber(dayStats[pointId] + hourData[pointId].stats.sum);
                });
            }
        });

        return dayStats;
    }

    // 从小时数据中聚合指定月份的数据（当月所有小时累计值的汇总）
    aggregateByMonth(targetMonth) {
        const monthStats = {};
        
        Object.keys(this.hourlyData).forEach(hourKey => {
            if (hourKey.startsWith(targetMonth)) {
                const hourData = this.hourlyData[hourKey];
                Object.keys(hourData).forEach(pointId => {
                    if (!monthStats[pointId]) {
                        monthStats[pointId] = 0;
                    }
                    // 累加该测点当月所有小时的sum值
                    monthStats[pointId] = formatNumber(monthStats[pointId] + hourData[pointId].stats.sum);
                });
            }
        });

        return monthStats;
    }

    // 计算日维度聚合（当天累计）
    calculateDaily() {
        debugLog('Calculating daily aggregation', { currentDay: this.currentDay });
        
        const dailyData = {};
        // 只计算当天
        dailyData[this.currentDay] = this.aggregateByDate(this.currentDay);

        return dailyData;
    }

    // 计算最近7天聚合（每天单独计算，然后提供7天总计）
    calculateWeekly() {
        debugLog('Calculating weekly aggregation (last 7 days)', { currentDay: this.currentDay });
        
        const weeklyData = {};
        const dates = generateDateRange(this.currentDate, CONFIG.RETENTION.WEEKLY_DAYS);
        
        // 每天单独计算
        dates.forEach(date => {
            weeklyData[date] = this.aggregateByDate(date);
        });

        // 计算7天总计
        const weeklyTotal = {};
        dates.forEach(date => {
            const dayData = weeklyData[date];
            Object.keys(dayData).forEach(pointId => {
                if (!weeklyTotal[pointId]) {
                    weeklyTotal[pointId] = 0;
                }
                weeklyTotal[pointId] = formatNumber(weeklyTotal[pointId] + dayData[pointId]);
            });
        });

        return {
            days: weeklyData,
            total: weeklyTotal
        };
    }

    // 计算最近30天聚合（每天单独计算，然后提供30天总计）
    calculateMonthly() {
        debugLog('Calculating monthly aggregation (last 30 days)', { currentDay: this.currentDay });
        
        const monthlyData = {};
        const dates = generateDateRange(this.currentDate, CONFIG.RETENTION.MONTHLY_DAYS);
        
        // 每天单独计算
        dates.forEach(date => {
            monthlyData[date] = this.aggregateByDate(date);
        });

        // 计算30天总计
        const monthlyTotal = {};
        dates.forEach(date => {
            const dayData = monthlyData[date];
            Object.keys(dayData).forEach(pointId => {
                if (!monthlyTotal[pointId]) {
                    monthlyTotal[pointId] = 0;
                }
                monthlyTotal[pointId] = formatNumber(monthlyTotal[pointId] + dayData[pointId]);
            });
        });

        return {
            days: monthlyData,
            total: monthlyTotal
        };
    }

    // 计算最近12个月聚合（每月单独计算，然后提供12个月总计）
    calculateYearly() {
        debugLog('Calculating yearly aggregation (last 12 months)', { currentMonth: this.currentMonth });
        
        const yearlyData = {};
        const monthKeys = generateMonthRange(this.currentDate, CONFIG.RETENTION.YEARLY_MONTHS);
        
        // 每月单独计算
        monthKeys.forEach(monthKey => {
            yearlyData[monthKey] = this.aggregateByMonth(monthKey);
        });

        // 计算12个月总计
        const yearlyTotal = {};
        monthKeys.forEach(monthKey => {
            const monthData = yearlyData[monthKey];
            Object.keys(monthData).forEach(pointId => {
                if (!yearlyTotal[pointId]) {
                    yearlyTotal[pointId] = 0;
                }
                yearlyTotal[pointId] = formatNumber(yearlyTotal[pointId] + monthData[pointId]);
            });
        });

        return {
            months: yearlyData,
            total: yearlyTotal
        };
    }

    // 执行完整聚合
    performAggregation() {
        const startTime = Date.now();
        
        const result = {
            daily: this.calculateDaily(),
            weekly: this.calculateWeekly(),
            monthly: this.calculateMonthly(),
            yearly: this.calculateYearly(),
            metadata: {
                lastUpdated: this.currentDate.toISOString(),
                processingTime: 0,
                dataPoints: {
                    hourly: Object.keys(this.hourlyData).length
                }
            }
        };

        // 统计处理时间
        result.metadata.processingTime = Date.now() - startTime;

        debugLog('Aggregation completed', result.metadata);
        return result;
    }
}

// 主执行逻辑
try {
    // 获取现有统计数据
    const existingStats = global.get('_STATISTICS_') || { byTimeDimension: {} };
    
    // 验证小时数据是否存在
    if (!existingStats.byTimeDimension || !existingStats.byTimeDimension.hourly) {
        node.warn("No hourly data found for aggregation");
        return msg;
    }

    debugLog('Starting aggregation process', {
        hourlyDataKeys: Object.keys(existingStats.byTimeDimension.hourly).length
    });

    // 创建聚合器并执行聚合
    const aggregator = new DataAggregator(existingStats.byTimeDimension.hourly);
    const aggregatedData = aggregator.performAggregation();

    // 更新统计数据结构，保持与原版本兼容的结构
    const updatedStats = {
        byMeasurementPoint: existingStats.byMeasurementPoint || {},
        byTimeDimension: {
            hourly: existingStats.byTimeDimension.hourly, // 保留原有小时数据
            daily: aggregatedData.daily,                   // 当天累计
            weekly: aggregatedData.weekly.days,            // 最近7天，每天单独
            monthly: aggregatedData.monthly.days,          // 最近30天，每天单独
            yearly: aggregatedData.yearly.months           // 最近12个月，每月单独
        },
        lastUpdated: aggregatedData.metadata.lastUpdated,
        // 额外保存汇总数据，供API查询使用
        aggregationSummary: {
            weeklyTotal: aggregatedData.weekly.total,      // 7天总计
            monthlyTotal: aggregatedData.monthly.total,    // 30天总计
            yearlyTotal: aggregatedData.yearly.total       // 12个月总计
        },
        aggregationMetadata: aggregatedData.metadata
    };

    // 保存更新后的统计数据
    global.set('_STATISTICS_', updatedStats);

    debugLog('Aggregation process completed successfully', {
        totalProcessingTime: aggregatedData.metadata.processingTime,
        dailyPoints: Object.keys(aggregatedData.daily).length,
        weeklyDays: Object.keys(aggregatedData.weekly.days).length,
        monthlyDays: Object.keys(aggregatedData.monthly.days).length,
        yearlyMonths: Object.keys(aggregatedData.yearly.months).length
    });

} catch (error) {
    node.error("Error in aggregation process: " + error.message);
    node.warn(error.stack);
}

return msg;